<?php

namespace App\Jobs;

use App\Constant\ThirdCommonCode;
use App\Exceptions\GeneralException;
use App\Facades\CommonPlatformRequestFacade;
use App\Library\String\Strings;
use App\Library\Traits\RepaySmsRemind;
use App\Models\RepayRecord;
use App\Models\UserGlobal;
use Carbon\Carbon;
use Exception;
use App\Constant\QueueKey;
use App\Models\RepayRecordCommon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\RepaySummary;
use App\Events\CollectionReceiptEvent;

class RepayCommonJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, RepaySmsRemind;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 300; //秒数

    /**
     * @var
     */
    protected $record_common_id;

    /**
     * RepayCommonJob constructor.
     * @param $record_common_id
     */
    public function __construct($record_common_id)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_COMMON_RESULT);
        $this->record_common_id = $record_common_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $t0 = microtime(true);
        $model = RepayRecordCommon::find($this->record_common_id);
        if (RepayRecordCommon::STATUS_TWO == $model->status) {
            $result = CommonPlatformRequestFacade::getCommonRepayResult([
                'channelId' => $model['third_record_id'],
                'orderId' => $model['trade_no'],
            ]);
            //payOrderNo
            $data = $result['data'];
            if (ThirdCommonCode::STATUS_ONE == $data['status']) {
                //成功
                $this->_success($model,$data);
                Log::debug('repay_get_common_result', ['message' => '处理成功']);
            } else if (ThirdCommonCode::STATUS_TWO == $data['status']) {
                //失败
                $this->_failure($model, $data);
                Log::debug('repay_get_common_result', ['message' => '处理失败']);
            } else {
                //未捕获结果 处理中
                Log::debug('repay_get_common_result', ['message' => '获取结果' . $data['status'], 'data' => $data]);
            }
            $this->delete();
        }
        $t1 = microtime(true);
        Log::debug('repay_get_common_result',['message' => '获取公共结果事件', 'second' => round($t1 - $t0,2)]);
        return ;
    }

    /**
     * 要处理的失败任务。
     *
     * @param  Exception  $exception
     * @return void
     */
    public function failed(Exception $exception){}

    /**
     * Description: 公共平台成功处理
     * Author: Gxs
     * @param RepayRecordCommon $model
     * @param array $data
     * @throws GeneralException
     */
    private function _success($model, $data = [])
    {
        RepayRecordCommon::setCommonSuccessStatus($model,$data);
    }

    /**
     * Description: 公共失败处理
     * Author: Gxs
     * @param RepayRecordCommon $model
     * @param $data
     * @return bool
     * @throws GeneralException
     */
    private function _failure($model, $data = [])
    {
        try {
            DB::beginTransaction();
            //公共表更新失败状态
            $model->where('id', $model->id)->update([
//                'pay_order_no' => isset($data['payOrderNo']) ? $data['payOrderNo'] : '', //京东商户订单号
                'status' => $model::STATUS_THREE,
                'failure' => isset($data['respMsg']) ? $data['respMsg'] : '未知错误',
                'status_time' => Carbon::now()
            ]);
            //记录总表更新失败理由
            $record = [
                'status' => RepayRecord::STATUS_THREE,
                'failure_status' => RepayRecord::FAILURE_STATUS_TWO,
                'failure_message' => isset($data['respMsg']) ? $data['respMsg'] : '还款失败',
            ];
            $model->record()->where('id', $model->record_id)->update($record);

            //用户全局状态变更
            UserGlobal::where('uid', $model->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);

            //如果是代扣Api调用对应事件

             event(new CollectionReceiptEvent($model->record_id));

            //最后顺序队列失败调用逻辑
            RepayRecord::setNormalOrderFailure($model);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new GeneralException($e->getMessage());
        }
        return true;
    }
}